package org.firegrid.view.zk;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.firegrid.core.spring.SpringObjectFactory;
import org.firegrid.model.FItem;
import org.firegrid.model.Form;
import org.firegrid.repository.FormRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.SuspendNotAllowedException;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.util.GenericForwardComposer;
import org.zkoss.zul.Listbox;
import org.zkoss.zul.Listcell;
import org.zkoss.zul.Listitem;
import org.zkoss.zul.Window;

public class FlowFSComposer extends GenericForwardComposer {

	/**
	 * 
	 */
	private static final long serialVersionUID = 5366581246941833747L;
	private Listbox fslistbox;
	private Form ppt;
	@Autowired
	private FormRepository formRepository;

	public FlowFSComposer() {
		SpringObjectFactory.autowire(this);
	}

	public void doAfterCompose(Component comp) throws Exception {
		super.doAfterCompose(comp);
		ppt = (Form) comp.getAttribute("parent");
		this.formRepository.save(ppt);
		initfs();
	}

	public void onAdd(Event event) {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("parent", ppt);
		Window win = (Window) Executions.createComponents(
				"/flow_design_fsEdit.zul", null, params);
		try {
			win.doModal();
			initfs();
		} catch (SuspendNotAllowedException e) {

		} catch (InterruptedException e) {

		}
	}

	private void initfs() {
		List<FItem> fitems = this.formRepository.getFItems(ppt);
		Listitem item = new Listitem();
		item.setParent(fslistbox);
		for (FItem fItem : fitems) {
			Listcell cname = new Listcell();
			cname.setLabel(fItem.getName());
			cname.setParent(item);
			
			Listcell ctype = new Listcell();
			ctype.setLabel(fItem.getType().name());
			ctype.setParent(item);
			
			Listcell caction = new Listcell();
			caction.setLabel(fItem.getType().name());
			caction.setParent(item);
			
		}
	}

	/**
	 * @param formRepository
	 *            the formRepository to set
	 */
	public void setFormRepository(FormRepository formRepository) {
		this.formRepository = formRepository;
	}
}
